package org.sith.taskrunner.ejb.transformers;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.sith.taskrunner.api.exceptions.TransformInputDataException;
import org.sith.taskrunner.api.task.TaskInputData;
import org.sith.taskrunner.api.transformer.InputDataTransofrmer;
import org.sith.taskrunner.ejb.tasks.SumInputData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class AbstractNormalAndSumXMLDataTransformer {

	public List<Double> getResultSequence(InputStream inputData)
			throws TransformInputDataException {
		List<Double> numerics = new ArrayList<Double>();
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(inputData);
			doc.getDocumentElement().normalize();
			NodeList nodeList = doc.getElementsByTagName("value");
			for (int i = 0; i < nodeList.getLength(); i++) {
				Node frstNode = nodeList.item(i);
				if (frstNode.getNodeType() == Node.ELEMENT_NODE) {
					Element fstElement = (Element) nodeList.item(i);
					NodeList val = fstElement.getChildNodes();
					numerics.add(new Double(val.item(0).getNodeValue()));
				}
			}
		} catch (IOException e) {
			throw new TransformInputDataException("Your data is not valid.", e);
		} catch (ParserConfigurationException pce) {
			throw new TransformInputDataException(
					"Server configuratin exception", pce);
		} catch (SAXException sax) {
			throw new TransformInputDataException("SAX Exception", sax);
		}
		return numerics;
	}

}
